package com.exp.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

/**
 *
 * @author zhangxj
 * @date 2025/1/2
 * @Description
 */
@Configuration
@EnableMethodSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authorize -> authorize
                        .anyRequest().authenticated()
                )
        .formLogin(withDefaults())
        .httpBasic(withDefaults());

        // 跨域
        http.cors(Customizer.withDefaults());
        // 禁用 csrf
        http.csrf(AbstractHttpConfigurer::disable);
        return http.build();
    }


    @Bean
    public UserDetailsService userDetailsService() {
        // 创建基于内存的用户信息管理器
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        // 使用 manager 管理用户对象
        manager.createUser(
                User.withDefaultPasswordEncoder().username("user").password("password")
                        .roles("USER")
                        .build()
        );
        manager.createUser(
                User.withDefaultPasswordEncoder().username("admin").password("password")
                        .roles("ADMIN")
                        .build()
        );
        return manager;
    }
}
